<template>
  <el-dialog title="修改密码" :visible="value" width="400px" custom-class="dialog-box" @close="onClose" @open="onOpen" :close-on-click-modal="false" :modal-append-to-body="false">
    <el-form @submit.native.prevent="onSubmit"  label-position="top" ref="form" :model="form" :rules="rules">
      <el-form-item label="原密码：" prop="oldPwd">
        <el-input v-model="form.oldPwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新密码：" prop="firstPwd">
        <el-input v-model="form.firstPwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码：" prop="secPwd">
        <el-input v-model="form.secPwd" type="password"></el-input>
      </el-form-item>
      <el-button v-show="false" :loading="btnLoading" native-type="submit" >提交</el-button>
    </el-form>
    <span slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="onSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { mapGetters } from "vuex";
export default {
  props: ["value"],
  data() {
    return {
      btnLoading: false,
      form: {
        oldPwd: "",
        firstPwd: "",
        secPwd: ""
      },
      rules: {
        oldPwd: [{ required: true, message: "此项必填", trigger: "blur" }],
        firstPwd: [
          { required: true, message: "此项必填", trigger: "blur" },
          { type: "string", min: 6, message: "格式不对" }
        ],
        secPwd: [
          { required: true, message: "此项必填", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              let th = this;
              if (value == th.form.firstPwd) {
                callback();
              } else {
                callback(new Error("两次密码不同"));
              }
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    onSubmit() {
      let th = this;
      let fn = () => {
        th.btnLoading = true;
        let j = { 
          oldPwd: hex_md5(th.form.oldPwd),
          memberId: th.adminUser.memberId,
          firstPwd: hex_md5(th.form.firstPwd),
          secPwd: hex_md5(th.form.secPwd)
        };
        th.$api.updatePwd(j).then(res => {
          if (res.executed) {
            th.$message.success("修改成功");
            th.onClose();
          } else {
            th.$message.error(res.message);
          }
          th.btnLoading = false;
        });
      };
      th.$refs["form"].validate(v => {
        if (v) {
          fn();
        }
      });
    },
    onClose() {
      let th = this;
      th.$refs["form"].resetFields();
      th.$emit("input", false);
    },
    onOpen() {}
  }
};
</script>
